<?php
class Server {
  public static function submit_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    $orm->update('pb_page', $req);
    Server::__clear();
    echo json_encode($req);
  }
  
  public static function update_objs($orm, $sys, $inst, $is_iframe) {
    $reqs = json_decode(Utils::get_param('reqs', '[]'));
    foreach ($reqs as &$itm) {
      $orm->update('pb_page', $itm);
    }
    Server::__clear();
  }
  
  public static function delete_obj($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    Server::__delete_obj($orm, $req);
    
    if ($req->is_default == 1) {
      $opts = new stdClass();
      $opts->cd .=  't.sys_id = :v1';
      $opts->cdv = array(':v1' => $req->sys_id);
      $rslt = $orm->get('pb_page', NULL, NULL, 1, 1, $opts)->d;
      if (count($rslt) > 0) {
        $rslt[0]->is_default = 1;
        $orm->update('pb_page', $rslt[0]);
      }
    }
    Server::__clear();
  }
  
  public static function __delete_obj($orm, $req) {
    $opts = new stdClass();
    $opts->cd = 'parent_id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $pages = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;
    foreach ($pages as &$page) {
      Server::__delete_obj($orm, $page);
    }
    $orm->delete('pb_page', $req);
    $opts = new stdClass();
    $opts->cd = 'page_id = :v1';
    $opts->cdv = array(':v1' => $req->id);
    $orm->delete_by_opts('pb_plugin_instance', $opts);
  }
  
  public static function __clear() {
    if (isset($_SESSION[SYS . 'index'])) {
      unset($_SESSION[SYS . 'index']);
    }
  }
}
?>